package middleware

import (
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"sensi/common/sys/logger"
	"time"
)

// Logger ...
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		traceId := uuid.NewV4().String()
		log := logger.DefaultLogger.With(zap.String("trace_id", traceId))
		c.Set("log", log)

		start := time.Now()
		c.Next()
		end := time.Now()
		latency := end.Sub(start)

		path := c.Request.URL.Path

		clientIP := c.ClientIP()
		method := c.Request.Method
		statusCode := c.Writer.Status()

		log.Info("access request",
			zap.Int("status code", statusCode),
			zap.Duration("letency", latency),
			zap.String("client ip", clientIP),
			zap.String("method", method),
			zap.String("path", path),
			zap.Any("query", c.Request.URL.Query()),
			zap.String("error", c.Errors.ByType(gin.ErrorTypePrivate).String()),
		)
	}
}
